package arch.dao.impl.user;

import java.io.Serializable;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import arch.dao.impl.user.mapper.ModuleMapper;
import arch.dao.user.ModuleDao;
import arch.domain.user.Module;
/**
 * 
 * @author ZhaoWangLong Sep 3, 2012
 *
 */
@Repository("moduleDao")
public class ModuleImpl implements ModuleDao {
	@Resource private JdbcTemplate jdbcTemplate;
	private final Logger logger = Logger.getLogger(ModuleImpl.class.getName());
	
	@SuppressWarnings("unchecked")
	public List<Module> queryList(String sql, boolean parent, Object... objects) {
		logger.debug("SQL > "+sql);
		return this.jdbcTemplate.query(sql, objects, new ModuleMapper(parent));
	}

	public Module find(Serializable primaryKey) {
		String sql = "select MODULE_ID, MODULE_NAME, INDEX, PMODULE, ACTION_URL,  " 
			+" IMAGE_URL, DESCRIPTION, CREATE_TIME, LAST_UPDATE_TIME from ID_MODULE where MODULE_ID = ? ";
		
		try {
			return (Module)this.jdbcTemplate.queryForObject(sql, new Object[]{primaryKey},new ModuleMapper(false));
		}catch (EmptyResultDataAccessException e) {
			return null;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public void merge(Module entity) {
		String sql = "update ID_MODULE set MODULE_NAME = ? , INDEX = ? , PMODULE = ? , ACTION_URL = ?, "
			+"IMAGE_URL = ? , DESCRIPTION = ?, LAST_UPDATE_TIME = ? where MODULE_ID = ? ";

		this.jdbcTemplate.update(sql, new Object[]{
			entity.getModuleName(),
			entity.getIndex(),
			entity.getPModule()==null?null:entity.getPModule().getModuleId(),
			entity.getActionUrl(),
			entity.getImageUrl(),
			entity.getDescription(),
			entity.getLastUpdateTime(),
			entity.getModuleId()
		});
	}

	public void persist(Module entity) {
		String sql = "insert into ID_MODULE (MODULE_ID, MODULE_NAME, INDEX, PMODULE, ACTION_URL, "
			+"IMAGE_URL, DESCRIPTION, CREATE_TIME, LAST_UPDATE_TIME) values (?,?,?,?,?,?,?,?,?)";

		this.jdbcTemplate.update(sql,new Object[]{
				entity.getModuleId(),
				entity.getModuleName(),
				entity.getIndex(),
				entity.getPModule()==null?null:entity.getPModule().getModuleId(),
				entity.getActionUrl(),
				entity.getImageUrl(),
				entity.getDescription(),
				entity.getCreateTime(),
				entity.getLastUpdateTime()
		});
	}

	public void remove(Serializable primaryKey) {
		String sql = "delete from ID_MODULE where MODULE_ID = ? ";
		
		this.jdbcTemplate.update(sql,new Object[]{primaryKey});
	}

	public Integer queryInt(String sql, Object... objects) {
		return this.jdbcTemplate.queryForInt(sql,objects);
	}

}
